package com.iwithlong.service.impl;

import com.imesne.assistant.common.bean.BeanKit;
import com.imesne.assistant.common.exception.ImesneException;
import com.imesne.assistant.common.page.PageList;
import com.imesne.assistant.common.validation.Verifier;
import com.imesne.assistant.jdbc.command.entity.Select;
import com.imesne.assistant.jdbc.persist.JdbcDao;
import com.iwithlong.entity.*;
import com.iwithlong.enums.ActivityAreaStatus;
import com.iwithlong.enums.ActivityStatus;
import com.iwithlong.enums.BizUploadFileType;
import com.iwithlong.enums.IndexType;
import com.iwithlong.service.ActivityAreaService;
import com.iwithlong.service.ActivityService;
import com.iwithlong.service.IndexService;
import com.iwithlong.utils.IndexUtils;
import com.iwithlong.utils.LuceneContext;
import com.iwithlong.vo.ActivityAreaVo;
import com.iwithlong.vo.ActivityVo;
import com.iwithlong.vo.SearchVo;
import com.iwithlong.vo.UploadFileVo;
import com.ktanx.platform.setting.kit.SettingKit;
import com.ktanx.platform.utils.HttpUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * Created by xiexiaohan on 2017/10/10.
 */
@Service
@Transactional
public class ActivityAreaServiceImpl implements ActivityAreaService{
    @Resource
    JdbcDao jdbcDao;

    @Resource
    IndexService indexService;

    @Resource
    ActivityService activityService;

    @Override
    public PageList<ActivityAreaVo> pageList(ActivityAreaVo activityAreaVo) {
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        if(StringUtils.isNotBlank(activityAreaVo.getKeyword())){
            activityAreaSelect.and().begin()
                    .condition("areaName","like",new Object[]{"%"+activityAreaVo.getKeyword()+"%"})
                    .or("brief","like",new Object[]{"%"+activityAreaVo.getKeyword()+"%"})
                    .or("areaIntroduction","like",new Object[]{"%"+activityAreaVo.getKeyword()+"%"})
                    .or("address","like",new Object[]{"%"+activityAreaVo.getKeyword()+"%"})
                    .end();
        }
        if(StringUtils.isNotBlank(activityAreaVo.getStatus())){
            activityAreaSelect.and("status",activityAreaVo.getStatus());
        }
        if(StringUtils.isNotBlank(activityAreaVo.getEnableSearch())){
            activityAreaSelect.and("enable",activityAreaVo.getEnableSearch());
        }
        if(StringUtils.isNotBlank(activityAreaVo.getCreator())){
            activityAreaSelect.and("creator",activityAreaVo.getCreator());
        }
        if(StringUtils.isNotBlank(activityAreaVo.getIssuer())){
            activityAreaSelect.and("issuer",activityAreaVo.getIssuer());
        }
        activityAreaSelect.orderBy("gmtModify").desc();
        PageList<ActivityArea> activityAreas = activityAreaSelect.pageList(activityAreaVo);
        List<ActivityAreaVo> activityVos = BeanKit.convert(ActivityAreaVo.class,activityAreas);
        for(ActivityAreaVo activityAreaVo1:activityVos){
            setActivityAreaUploadFiles(activityAreaVo1);
        }
        PageList<ActivityAreaVo> result = new PageList<>(activityVos,activityAreas.getPager());
        return result;
    }

    /**
     * 设置活动点的图片
     * @param activityAreaVo
     */
    private void setActivityAreaUploadFiles(ActivityAreaVo activityAreaVo){
        //查找对应业务文件
        Select<BizUploadFile> bizUploadFileSelect = jdbcDao.createSelect(BizUploadFile.class).where("1",1);
        bizUploadFileSelect.and("bizId",activityAreaVo.getActivityAreaId());
        bizUploadFileSelect.and("bizType",BizUploadFileType.ACTIVITYAREA.getCode());
        BizUploadFile bizUploadFile = bizUploadFileSelect.singleResult();
        if(bizUploadFile==null){
            activityAreaVo.setUploadFileVos(new ArrayList<UploadFileVo>());
            return;
        }
        //查找图片
        Select<UploadFile> uploadFileSelect = jdbcDao.createSelect(UploadFile.class).where("1",1);
        uploadFileSelect.and("bizUploadFileId",bizUploadFile.getBizUploadFileId());
        uploadFileSelect.orderBy("ord").asc();
        List<UploadFile> uploadFiles = uploadFileSelect.list();
        activityAreaVo.setUploadFileVos(BeanKit.convert(UploadFileVo.class,uploadFiles));
    }

    @Override
    public void deleteByIds(Long[] activityAreaIds) {
        Verifier.init().notEmpty(activityAreaIds, "id").validate();

        for(int i=0;i<activityAreaIds.length;i++){
            Select<Activity> activitySelect = jdbcDao.createSelect(Activity.class).where("1",1);
            activitySelect.and("activityAreaId",activityAreaIds[i]);
            if(activitySelect.list().size()>0){
                throw new ImesneException("该活动点下还有活动，清先删除活动");
            }
            //删除图片
            Select<BizUploadFile> bizUploadFileSelect = jdbcDao.createSelect(BizUploadFile.class).where("1",1);
            bizUploadFileSelect.and("bizType",BizUploadFileType.ACTIVITYAREA.getCode());
            bizUploadFileSelect.and("bizId",activityAreaIds[i]);
            BizUploadFile bizUploadFile = bizUploadFileSelect.singleResult();
            if(bizUploadFile!=null){
                Select<UploadFile> uploadFileSelect = jdbcDao.createSelect(UploadFile.class).where("1",1);
                uploadFileSelect.and("bizUploadFileId",bizUploadFile.getBizUploadFileId());
                List<UploadFile> uploadFiles = uploadFileSelect.list();
                for(UploadFile uploadFile:uploadFiles){
                    jdbcDao.delete(uploadFile);
                }
                jdbcDao.delete(bizUploadFile);
            }
            ActivityArea activityArea = new ActivityArea();
            activityArea.setActivityAreaId(activityAreaIds[i]);
            jdbcDao.delete(activityArea);
        }
        for(int i=0;i<activityAreaIds.length;i++){
            indexService.deleteIndex(String.valueOf(activityAreaIds[i]), IndexType.ACTIVITY_AREA.getCode());
        }
    }

    /**
     * 将需要修改的活动点属性复制给实体
     * @param activityArea
     * @param activityAreaVo
     */
    private void insertActivityAreaValues(ActivityArea activityArea,ActivityAreaVo activityAreaVo){
        activityArea.setAreaName(activityAreaVo.getAreaName());
        activityArea.setBrief(activityAreaVo.getBrief());
        activityArea.setAddress(activityAreaVo.getAddress());
        activityArea.setAreaIntroduction(activityAreaVo.getAreaIntroduction());
        activityArea.setCity(activityAreaVo.getCity());
        activityArea.setDistrict(activityAreaVo.getDistrict());
        activityArea.setLatitude(activityAreaVo.getLatitude());
        activityArea.setLongitude(activityAreaVo.getLongitude());
        activityArea.setProvince(activityAreaVo.getProvince());
        activityArea.setStatus(activityAreaVo.getStatus());
        activityArea.setModifier(activityAreaVo.getModifier());
        activityArea.setStatus(activityAreaVo.getStatus());
    }

    @Override
    public void update(ActivityAreaVo activityAreaVo,String bizUploadFileIds) {
        initActivityAreaVoUploads(activityAreaVo,bizUploadFileIds);
        Verifier.init().maxLength(activityAreaVo.getAreaName(),100,"活动点名称")
                .notBlank(activityAreaVo.getAreaName(),"活动点名称").notBlank(activityAreaVo.getAreaIntroduction(),"活动点简介").validate();
        //验证是否需要审核，如果需要，则不能直接发布
        if(StringUtils.equals(SettingKit.getValue("activityAreaAudit"),"true")){
            if(StringUtils.equals(activityAreaVo.getStatus(),ActivityAreaStatus.ISSUERED.getCode())){
                throw new ImesneException("需要通过审核才能发布");
            }
        }
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("activityAreaId",activityAreaVo.getActivityAreaId());
        ActivityArea activityArea = activityAreaSelect.singleResult();
        String oldStatus = activityArea.getStatus();
        String newStaus = activityAreaVo.getStatus();
        //判断活动点名称是否已经存在
        if(!StringUtils.equals(activityAreaVo.getAreaName(),activityArea.getAreaName())){
            Select<ActivityArea> activityAreaSelect1 = jdbcDao.createSelect(ActivityArea.class).where("1",1);
            activityAreaSelect1.and("areaName",activityAreaVo.getAreaName());
            List<ActivityArea> sameNameActivityAreaList = activityAreaSelect1.list();
            if(CollectionUtils.isNotEmpty(sameNameActivityAreaList)&&(sameNameActivityAreaList.get(0).getActivityAreaId()!=activityAreaVo.getActivityAreaId())){
                throw new ImesneException("存在相同的活动点名称");
            }
        }
        insertActivityAreaValues(activityArea,activityAreaVo);
        Date date = new Date();
        activityArea.setGmtModify(date);
        if(StringUtils.equals(activityAreaVo.getStatus(),ActivityAreaStatus.ISSUERED.getCode())){
            activityArea.setGmtIssue(date);
            activityArea.setIssuer(HttpUtils.getLoginUser().getUsername());
        }
        jdbcDao.update(activityArea);
        //更新活动点的图片
        String[] newUploadFiles = bizUploadFileIds.split(",");
        //获取原先绑定的图片
        Select<BizUploadFile> bizUploadFileSelect = jdbcDao.createSelect(BizUploadFile.class).where("1",1);
        bizUploadFileSelect.and("bizId",activityArea.getActivityAreaId());
        bizUploadFileSelect.and("bizType",BizUploadFileType.ACTIVITYAREA.getCode());
        BizUploadFile bizUploadFile = bizUploadFileSelect.singleResult();
        Select<UploadFile> uploadFileSelect = jdbcDao.createSelect(UploadFile.class).where("1",1);
        uploadFileSelect.and("bizUploadFileId",bizUploadFile.getBizUploadFileId());
        List<UploadFile> oldUploadFiles = uploadFileSelect.list();
        long order = 1;
        String firstPicUrl = "";
        for(int i=0;i<newUploadFiles.length;i++){
            if(StringUtils.isBlank(newUploadFiles[i])){
                continue;
            }
            boolean create = true;
            for(UploadFile uploadFile:oldUploadFiles){
                if(uploadFile.getUploadFileId().longValue()==Long.valueOf(newUploadFiles[i]).longValue()){
                    create = false;
                    uploadFile.setOrd(order);
                    jdbcDao.update(uploadFile);
                    oldUploadFiles.remove(uploadFile);
                    break;
                }
            }
            if(create){
                Select<UploadFile> uploadFileSelect1 = jdbcDao.createSelect(UploadFile.class).where("1",1);
                uploadFileSelect1.and("uploadFileId",Long.valueOf(newUploadFiles[i]));
                UploadFile uploadFile = uploadFileSelect1.singleResult();
                if(uploadFile==null){
                    throw new ImesneException("图片有误");
                }
                uploadFile.setOrd(order);
                uploadFile.setBizUploadFileId(bizUploadFile.getBizUploadFileId());
                jdbcDao.update(uploadFile);
            }
            if(order==1){
                firstPicUrl = newUploadFiles[i];
            }
            order++;
        }
        //删除原先的多余图片
        for(UploadFile uploadFile:oldUploadFiles){
            jdbcDao.delete(uploadFile);
        }

        ActivityAreaVo activityAreaVo1 = BeanKit.convert(new ActivityAreaVo(),activityArea);
        activityAreaVo1.setFirstPicUrl(firstPicUrl);
        if(StringUtils.equals(oldStatus,ActivityAreaStatus.ISSUERED.getCode())){
            if(!StringUtils.equals(newStaus,ActivityAreaStatus.ISSUERED.getCode())){
                indexService.deleteIndex(String.valueOf(activityAreaVo1.getActivityAreaId()),IndexType.ACTIVITY_AREA.getCode());
            }else {
                indexService.updateActivityAreaIndex(activityAreaVo1);
            }
        }else {
            if(StringUtils.equals(newStaus,ActivityAreaStatus.ISSUERED.getCode())){
                indexService.addActivityAreaIndex(activityAreaVo1);
            }
        }

    }

    private void initActivityAreaVoUploads(ActivityAreaVo activityAreaVo,String uploadFileIds){
        String[] uploadStrs = uploadFileIds.split(",");
        List<UploadFileVo> fileVos = new ArrayList<>();
        for (int i=0;i<uploadStrs.length;i++){
            if(StringUtils.isNotBlank(uploadStrs[i])){
                Select<UploadFile> select = jdbcDao.createSelect(UploadFile.class).where("1",1);
                select.and("uploadFileId",Long.valueOf(uploadStrs[i]));
                UploadFile uploadFile = select.singleResult();
                if(uploadFile==null){
                    continue;
                }
                fileVos.add(BeanKit.convert(new UploadFileVo(),uploadFile));
            }
        }
        activityAreaVo.setUploadFileVos(fileVos);
    }

    @Override
    public void add(ActivityAreaVo activityAreaVo,String uploadFileIds) {
        initActivityAreaVoUploads(activityAreaVo,uploadFileIds);
        Verifier.init().maxLength(activityAreaVo.getAreaName(),100,"活动点名称")
                .notBlank(activityAreaVo.getAreaName(),"活动点名称").notBlank(activityAreaVo.getBrief(),"活动点简称").notBlank(activityAreaVo.getAreaIntroduction(),"活动点介绍").validate();
        Select<ActivityArea> areaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        areaSelect.and("areaName",activityAreaVo.getAreaName());
        if(areaSelect.singleResult()!=null){
            throw new ImesneException("活动点名已存在");
        }
        ActivityArea activityArea = BeanKit.convert(new ActivityArea(),activityAreaVo);
        activityArea.setGmtCreate(new Date());
        activityArea.setGmtModify(new Date());
        activityArea.setStatus(activityAreaVo.getStatus());
        Long activityAreaId = (Long)jdbcDao.insert(activityArea);
        activityArea.setActivityAreaId(activityAreaId);
        //将图片和活动点关联起来
        BizUploadFile bizUploadFile = new BizUploadFile();
        bizUploadFile.setBizId(activityArea.getActivityAreaId());
        bizUploadFile.setBizType(BizUploadFileType.ACTIVITYAREA.getCode());
        //插入业务文件
        Long insert = (Long)jdbcDao.insert(bizUploadFile);
        bizUploadFile.setBizUploadFileId(insert);
        String[] uploadFiles = uploadFileIds.split(",");
        long order = 1;
        for(int i=0;i<uploadFiles.length;i++){
            if(StringUtils.isNotBlank(uploadFiles[i])){
                Select<UploadFile> select = jdbcDao.createSelect(UploadFile.class).where("1",1);
                select.and("uploadFileId",Long.valueOf(uploadFiles[i]));
                UploadFile uploadFile = select.singleResult();
                if(bizUploadFile==null){
                    throw new ImesneException("找不到图片");
                }
                uploadFile.setBizUploadFileId(bizUploadFile.getBizUploadFileId());
                uploadFile.setOrd(order);
                jdbcDao.update(uploadFile);
                order++;
            }
        }
    }

    @Override
    public ActivityAreaVo findById(long activityAreaId) {
        Verifier.init().notNull(activityAreaId,"id").validate();
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("activityAreaId",activityAreaId);
        ActivityArea activityArea = activityAreaSelect.singleResult();
        ActivityAreaVo activityAreaVo = BeanKit.convert(new ActivityAreaVo(),activityArea);
        setActivityAreaUploadFiles(activityAreaVo);
        return activityAreaVo;
    }

    @Override
    public List<ActivityAreaVo> mobilePageList(SearchVo searchVo) {
        List<ActivityAreaVo> activityAreaVos = findActivityAreaAndActivityByCorner(searchVo);
        return activityAreaVos;
    }

    @Override
    public ActivityAreaVo mobileFindById(Long activityAreaId,String weixin) {
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("activityAreaId",activityAreaId);
        ActivityArea activityArea = activityAreaSelect.singleResult();
        ActivityAreaVo activityAreaVo = BeanKit.convert(new ActivityAreaVo(),activityArea);
//        Select<Activity> activitySelect = jdbcDao.createSelect(Activity.class).where("1",1);
//        activitySelect.and("activityAreaId",activityAreaId);
//        activitySelect.and("status",ActivityStatus.ISSUERED);
//        activitySelect.and("gmtIssue",">",new Object[]{new Date()});
//        List<Activity> activities = activitySelect.list();
//        List<ActivityVo> activityVos = BeanKit.convert(ActivityVo.class,activities);
        setActivityAreaUploadFiles(activityAreaVo);
//        Select<Interest> interestSelect = jdbcDao.createSelect(Interest.class).where("1",1);
//        interestSelect.and("owner",weixin);
//        List<Interest> allInterest = interestSelect.list();
//        List<Long> activityIds = new ArrayList<>();
//        for (Interest interest : allInterest) {
//            activityIds.add(interest.getActivityId());
//        }
//        for(ActivityVo activityVo: activityVos){
//            if(activityIds.contains(activityVo.getActivityId())){
//                activityVo.setInterest(true);
//            }
//            activityService.setActivityUploadFiles(activityVo);
//        }
        SearchVo searchVo = new SearchVo();
        searchVo.setActivityAreaId(activityAreaVo.getActivityAreaId());
        searchVo.setWeixin(weixin);
        List<ActivityVo> activityVos = activityService.searchActivity(searchVo);
        activityAreaVo.setActivityVos(activityVos);
        return activityAreaVo;
    }

    @Override
    public void enableActivityArea(long activityAreaId) {
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("activityAreaId",activityAreaId);
        ActivityArea activityArea = activityAreaSelect.singleResult();
        activityArea.setEnable(activityArea.isEnable()?false:true);
        activityArea.setGmtModify(new Date());
        activityArea.setModifier(HttpUtils.getLoginUser().getUsername());
        jdbcDao.update(activityArea);
        if(StringUtils.equals(activityArea.getStatus(),ActivityAreaStatus.ISSUERED.getCode())){
            ActivityAreaVo activityAreaVo = BeanKit.convert(new ActivityAreaVo(),activityArea);
            activityAreaVo.setFirstPicUrl(findActivityAreaFirstPicUrl(activityAreaId));
            indexService.updateActivityAreaIndex(activityAreaVo);
        }
    }

    private String findActivityAreaFirstPicUrl(Long activityAreaId){
        Select<BizUploadFile> bizUploadFileSelect = jdbcDao.createSelect(BizUploadFile.class).where("1",1);
        bizUploadFileSelect.and("bizType",BizUploadFileType.ACTIVITYAREA.getCode());
        bizUploadFileSelect.and("bizId",activityAreaId);
        BizUploadFile bizUploadFile = bizUploadFileSelect.singleResult();
        if(bizUploadFile==null){
            return "";
        }
        Select<UploadFile> uploadFileSelect = jdbcDao.createSelect(UploadFile.class).where("1",1);
        uploadFileSelect.and("bizUploadFileId",bizUploadFile.getBizUploadFileId());
        uploadFileSelect.and("ord",1);
        UploadFile uploadFile = uploadFileSelect.singleResult();
        if(uploadFile==null){
            return "";
        }else {
            return uploadFile.getFileUrl();
        }
    }

    @Override
    public void audit(ActivityAreaVo activityAreaVo) {
        if(StringUtils.equals(activityAreaVo.getStatus(),ActivityAreaStatus.REVIEWREFUSED.getCode())){
            Verifier.init().notEmpty(activityAreaVo.getReason().trim(),"审核失败原因").validate();
        }
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("activityAreaId",activityAreaVo.getActivityAreaId());
        ActivityArea activityArea = activityAreaSelect.singleResult();
        if(activityArea==null){
            throw new ImesneException("找不到该活动点");
        }
        Date date = new Date();
        if(StringUtils.equals(activityAreaVo.getStatus(),ActivityAreaStatus.REVIEWED.getCode())){
            activityArea.setStatus(ActivityAreaStatus.REVIEWED.getCode());
            activityArea.setReason("");
        }else {
            activityArea.setStatus(ActivityAreaStatus.REVIEWREFUSED.getCode());
            activityArea.setReason(activityAreaVo.getReason());
        }
        activityArea.setAuditor(HttpUtils.getLoginUser().getUsername());
        activityArea.setGmtAudit(date);
        jdbcDao.update(activityArea);
//        if(StringUtils.equals(activityAreaVo.getStatus(),ActivityAreaStatus.REVIEWED.getCode())){
//            ActivityAreaVo activityAreaVo1 = BeanKit.convert(new ActivityAreaVo(),activityArea);
//            activityAreaVo1.setFirstPicUrl(findActivityAreaFirstPicUrl(activityArea.getActivityAreaId()));
//            indexService.addActivityAreaIndex(activityAreaVo1);
//        }
    }

	@Override
	public List<ActivityAreaVo> findActivityAreaByCorner (SearchVo searchVo) {
        BooleanQuery booleanQuery = new BooleanQuery();

        //经度
        Query xQuery= NumericRangeQuery.newDoubleRange ("longitude", searchVo.getXleft (), searchVo.getXright (), true, true);
        booleanQuery.add (xQuery, BooleanClause.Occur.MUST);

        //纬度
        Query yQuery= NumericRangeQuery.newDoubleRange ("latitude", searchVo.getYright (), searchVo.getYleft (), true, true);
        booleanQuery.add (yQuery, BooleanClause.Occur.MUST);

        //审核通过
        Query queryStatus = new TermQuery(new Term ("status",ActivityAreaStatus.ISSUERED.getCode ()));
        booleanQuery.add (queryStatus, BooleanClause.Occur.MUST);

        //启用
        Query queryEnabel = new TermQuery(new Term ("enable", "true"));
        booleanQuery.add (queryEnabel, BooleanClause.Occur.MUST);

        //索引类型为活动点
        Query queryIndexType = new TermQuery(new Term ("indexType", IndexType.ACTIVITY_AREA.getCode ()));
        booleanQuery.add (queryIndexType, BooleanClause.Occur.MUST);

		//发布时间 取今天之前的数据
		Query gmtIssue= NumericRangeQuery.newLongRange ("gmtIssue", 0L, new Date ().getTime (), true, true);
		booleanQuery.add (gmtIssue, BooleanClause.Occur.MUST);


        //排序
        Sort sort=new Sort();
        SortField defField=new SortField("activityAreaId", SortField.STRING,true);
        sort.setSort (defField);


        IndexSearcher searcher = LuceneContext.getInstance ().getSearcher ();

        List<Document> documentList=new ArrayList<> ();
        try {
            TopDocs docs = searcher.search (booleanQuery, searchVo.getPageSize(),sort);

            for (ScoreDoc scoreDoc : docs.scoreDocs) {

                Document document=searcher.doc (scoreDoc.doc);

                documentList.add (document);
            }


        } catch (IOException e) {
            e.printStackTrace ();
        }

        return IndexUtils.docs2ActivityAreaList (documentList);
	}

    @Override
    public List<ActivityAreaVo> findActivityAreaAndActivityByCorner (SearchVo searchVo) {

        List<ActivityAreaVo> activityAreaByCorner = findActivityAreaByCorner (searchVo);
        Map<Long,ActivityAreaVo> maps = new HashMap<>();


        for (ActivityAreaVo activityAreaVo : activityAreaByCorner) {
            maps.put(activityAreaVo.getActivityAreaId(),activityAreaVo);

            BooleanQuery booleanQuery = new BooleanQuery();

            Query activityAreaIdQuery= NumericRangeQuery.newLongRange ("activityAreaId", activityAreaVo.getActivityAreaId (), activityAreaVo.getActivityAreaId (), true, true);
            booleanQuery.add (activityAreaIdQuery, BooleanClause.Occur.MUST);

            //活动审核通过
            Query queryStatus = new TermQuery(new Term ("status", ActivityStatus.ISSUERED.getCode ()));
            booleanQuery.add (queryStatus, BooleanClause.Occur.MUST);
            //活动启用
            Query queryEnabel = new TermQuery(new Term ("enable", "true"));
            booleanQuery.add (queryEnabel, BooleanClause.Occur.MUST);


            //活动点审核通过
            Query queryActivityAreaStatus = new TermQuery(new Term ("activityAreaStatus", ActivityAreaStatus.ISSUERED.getCode ()));
            booleanQuery.add (queryActivityAreaStatus, BooleanClause.Occur.MUST);
            //活动点启用
            Query queryActivityAreaEnabel = new TermQuery(new Term ("activityAreaEnable", "true"));
            booleanQuery.add (queryActivityAreaEnabel, BooleanClause.Occur.MUST);

            //索引类型为活动
            Query queryIndexType = new TermQuery(new Term ("indexType", IndexType.ACTIVITY.getCode ()));
            booleanQuery.add (queryIndexType, BooleanClause.Occur.MUST);

            //发布时间 取今天之前的数据
            Query gmtIssue= NumericRangeQuery.newLongRange ("gmtIssue", 0L, new Date ().getTime (), true, true);
            booleanQuery.add (gmtIssue, BooleanClause.Occur.MUST);

            Sort sort=new Sort();
            SortField weightSortField=new SortField("weight", SortField.LONG,true);
            sort.setSort (weightSortField);

            IndexSearcher searcher = LuceneContext.getInstance ().getSearcher ();

            try {
                TopDocs docs = searcher.search (booleanQuery,100,sort);

                List<Document> documentList=new ArrayList<> ();

                for (ScoreDoc scoreDoc : docs.scoreDocs) {

                    Document document=searcher.doc (scoreDoc.doc);

                    documentList.add (document);
                }

                List<ActivityVo> activityVos = IndexUtils.docs2ActivityList (documentList);
                if(StringUtils.isNotBlank(searchVo.getWeixin())){
                    for (ActivityVo activityVo : activityVos) {
                        String weixinStrs = activityVo.getWeixinStrs();
                        if(StringUtils.isNotBlank(weixinStrs)){
                            List<String> weixinArray = Arrays.asList(weixinStrs.split(","));
                            if(weixinArray.contains(searchVo.getWeixin())){
                                activityVo.setInterest(true);
                            }
                        }
                    }
                }
                activityAreaVo.setActivityVos (activityVos);

            } catch (IOException e) {
                e.printStackTrace ();
            }
        }
        //比较活动点的第一个活动的权重，按降序排列
        Collections.sort(activityAreaByCorner, new Comparator<ActivityAreaVo>() {
            @Override
            public int compare(ActivityAreaVo o1, ActivityAreaVo o2) {
                if(CollectionUtils.isNotEmpty(o1.getActivityVos())&&CollectionUtils.isNotEmpty(o2.getActivityVos())){
                    if(o1.getActivityVos().get(0).getWeight()>o2.getActivityVos().get(0).getWeight()){
                        return -1;
                    }else if(o1.getActivityVos().get(0).getWeight()==o2.getActivityVos().get(0).getWeight()){
                        return 0;
                    }else {
                        return 1;
                    }
                }
                if(CollectionUtils.isNotEmpty(o1.getActivityVos())){
                    return -1;
                }
                if(CollectionUtils.isNotEmpty(o2.getActivityVos())){
                    return 1;
                }
                return 0;
            }
        });

        return activityAreaByCorner;
    }

    @Override
    public List<ActivityAreaVo> findAllEnable() {
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("status",ActivityAreaStatus.ISSUERED.getCode());
        List<ActivityAreaVo> activityAreaVos = BeanKit.convert(ActivityAreaVo.class,activityAreaSelect.list());
        for (ActivityAreaVo activityAreaVo : activityAreaVos) {
            activityAreaVo.setFirstPicUrl(findActivityAreaFirstPicUrl(activityAreaVo.getActivityAreaId()));
        }
        return activityAreaVos;
    }

    @Override
    public List<ActivityAreaVo> filter(ActivityAreaVo activityAreaVo) {
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        if(StringUtils.isNotBlank(activityAreaVo.getAreaName())){
            activityAreaSelect.and("areaName","like",new Object[]{"%"+activityAreaVo.getAreaName()+"%"});
        }
        activityAreaSelect.orderBy("gmtCreate").desc();
        PageList<ActivityArea> activityAreas = activityAreaSelect.pageList(activityAreaVo);
        List<ActivityAreaVo> activityVos = BeanKit.convert(ActivityAreaVo.class,activityAreas);
        return activityVos;
    }

    @Override
    public boolean existAreaName(String areaName) {
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("areaName",areaName);
        ActivityArea activityArea = activityAreaSelect.singleResult();
        if(activityArea==null){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public void IssuerActivityArea(ActivityAreaVo activityAreaVo) {
        Long activityAreaId = activityAreaVo.getActivityAreaId();
        Date gmtIssuer = activityAreaVo.getGmtIssue();
        String issuer = activityAreaVo.getIssuer();
        Verifier.init().notNull(activityAreaId,"活动点Id").notNull(gmtIssuer,"发布时间").notBlank(issuer,"发布人").validate();
        Select<ActivityArea> activityAreaSelect = jdbcDao.createSelect(ActivityArea.class).where("1",1);
        activityAreaSelect.and("activityAreaId",activityAreaId);
        ActivityArea activityArea = activityAreaSelect.singleResult();
        activityArea.setEnable(true);
        if(activityArea==null){
            throw new ImesneException("活动点不存在");
        }
        if(StringUtils.equals(activityArea.getStatus(),ActivityAreaStatus.ISSUERED.getCode())){
            throw new ImesneException("活动点已经发布过");
        }
        activityArea.setIssuer(issuer);
        activityArea.setGmtIssue(gmtIssuer);
        activityArea.setStatus(ActivityAreaStatus.ISSUERED.getCode());
        jdbcDao.update(activityArea);
        ActivityAreaVo activityAreaVo1 = BeanKit.convert(new ActivityAreaVo(),activityArea);
        activityAreaVo1.setFirstPicUrl(findActivityAreaFirstPicUrl(activityArea.getActivityAreaId()));
        indexService.addActivityAreaIndex(activityAreaVo1);
    }


}
